import React from 'react'
import ReactDOM from 'react-dom';
import moment from 'moment'

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {actions} from '../../../reducers'
import { actions as PAction } from '../../../reducers/project'

import { ListView } from 'antd-mobile'
import { Link } from 'react-router-dom'
import {MyBody, genData, separator} from 'components/listview-func'

import utils from '../../../common/utils'


class List extends React.Component {
    constructor(props) {
        super(props)
        this.dataBlob = {};

		const getSectionData = (dataBlob, sectionID) => this.dataBlob[sectionID];
		const getRowData = (dataBlob, sectionID, rowID) => { return dataBlob[sectionID] ? dataBlob[sectionID][rowID] : null};
	
        const dataSource = new ListView.DataSource({
            getRowData,
            getSectionHeaderData: getSectionData,
            rowHasChanged: (row1, row2) => row1 !== row2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
        });
	
		this.state = {
            i: 0,
            dataSource,
            isLoading: true,
            height: document.documentElement.clientHeight,
            hasMore: true,
            conditions: this.props.conditions,
            refresh: false
		}
    }

    componentDidMount() {
        let type = window.location.pathname.split("/").pop()
        console.log(type)
		this.setState({type})
        this.props.get_project_list(type, 1, this.resolveSearch(this.state.conditions))

        const height = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop - 127;
        this.setState({height})
        this.props.get_project_list(type, 1, this.resolveSearch(this.state.conditions))
    }

    componentWillReceiveProps(nextProps) {
        let refresh = JSON.stringify(nextProps.conditions) != JSON.stringify(this.props.conditions)
        if (refresh) {
            this.props.get_project_list(this.state.type, 1, this.resolveSearch(nextProps.conditions))
            this.setState({conditions: nextProps.conditions, refresh: refresh})
        }
       
		if (nextProps.project_list !== this.props.project_list) {
            this.state.refresh ? this.dataBlob = {} : null
            let {dataBlobs, sectionIDs, rowIDs} = genData(this.dataBlob, nextProps.current_page, nextProps.project_list)
			this.setState({
                refresh: false,
				isLoading: false,
				hasMore: nextProps.total > nextProps.per_page*nextProps.current_page,
				dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlobs, sectionIDs, rowIDs),
            });
        }
        
    }	

    onEndReached = (event) => {
        if (this.state.isLoading || !this.state.hasMore) {
			return;
		}
		this.setState({ isLoading: true });
		this.props.get_project_list(this.state.type, this.props.current_page+1, this.resolveSearch(this.props.conditions))
    }

    resolveSearch = (conditions) => {
        let search = ''
        conditions.forEach( (ele) => {
            if (ele.type=='sort') {
                search += `&sortKey=${ele.value}&sortValue=${ele.order}`
            } else {
                search += `&${ele.type}=${ele.value}`
            }
        })
        return search
    }
    
    render() {
        const row = (rowData, sectionID, rowID) => {
            
            let _url = {pathname:`/project-detail/introduction/${this.state.type}`,
             search: `?type=${this.state.type}&id=${rowData.id}&project_id=${rowData.project_id}`}
            let _class = () => {
                switch (rowData.status) {
                    case 'done':
                        return 'a2'
                    case 'draft':
                        return 'a3'
                    case 'pending':
                        return 's1'    
                    default:
                        return ''
                }
            },
            _last = utils.getLastTime(rowData.expect_at)
            return (
                <Link to={_url}>
                    <dl className="clearfix">
                        <dt className="col-xs-4"><img src={require('../images/a1.jpg')} /></dt>
                        <dd className="col-xs-8">
                            <div className="p1">
                                <span className={rowData.is_show_red_dot?'red-dot': ''}>{rowData.title}</span>
                                <i>{this.props.showPublisher?`发布者：${rowData.user.nickname}`:null}</i>
                            </div>
                            <div className="p2">
                                <span>{moment(rowData.created_at).format('YYYY-MM-DD hh:mm')}</span>
                                {
                                    rowData.status == 'pending' ?
                                        <label class={_class()}>
                                            <em>投标</em>
                                            {
                                            _last.overtime?'超时':'剩余'
                                            }
                                            <tt>{Math.abs(_last.d)}</tt>天<tt>{Math.abs(_last.h)}</tt>小时
                                        </label>
                                    :   <i class={_class()}>
                                            {utils.formatProjectStatus(rowData)}
                                        </i>
                                }
                                
                            </div>
                        </dd>
                    </dl>
                </Link>
            );
        };

        return (
                <ListView
                    ref={el => this.lv = el}
                    dataSource={this.state.dataSource}
                    renderFooter={() => (<div style={{ textAlign: 'center' }}>
                        {this.state.isLoading ? '正在加载...' : (this.state.hasMore ? '还有更多项' : '已经是最后一条记录')}
                        </div>)}
                    renderBodyComponent={() => <MyBody classname='my-list'/>}
                    renderRow={row}
                    style={{
                        height: this.state.height,
                        overflow: 'auto',
                    }}
                    initialListSize={5}
                    pageSize={5}
                    onScroll={() => { console.log('scroll'); }}
                    scrollRenderAheadDistance={500}
                    onEndReached={this.onEndReached}
                    onEndReachedThreshold={10}
                    scrollerOptions={{ scrollbars: true }}
                />
        )
    }
}

function mapStateToProps(state) {
    return {
      project_list: state.project.list,
      current_page: state.project.current_page,
      per_page: state.project.per_page,
      total: state.project.total,
      
    }
}
  
function mapDispatchToProps(dispatch) {
    return  {
        get_project_list: bindActionCreators(PAction.get_list, dispatch)
    }
}
  
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(List)